<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.roleName" size="small" clearable placeholder="输入名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="520px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" style="width: 380px;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" style="width: 380px;" rows="5" type="textarea" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column :show-overflow-tooltip="true" prop="remark" label="描述" />
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间" />
            <el-table-column v-if="checkPer(['admin','sys:role:update','sys:role:delete'])" label="操作" width="130px" align="center" fixed="right">
              <template slot-scope="scope">
                <udOperation
                  :data="scope.row"
                  :permission="permission"
                />
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['admin','sys:role:update']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIdList"
            accordion
            show-checkbox
            node-key="menuId"
            @check="menuChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudRoles from '@/api/sys/role'
import { getMenuList } from '@/api/sys/menu'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { list_to_vuetree } from '@/utils'

const defaultForm = { roleId: null, name: null, remark: null, menuIdList: [] }
export default {
  name: 'Role',
  components: { pagination, crudOperation, rrOperation, udOperation },
  cruds() {
    return CRUD({ title: '角色', url: '/sys/role/list', crudMethod: { ...crudRoles }, idField: "roleId" })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      currentId: 0, menuLoading: false, showButton: false,
      menus: [], menuIdList: [], // 多选时使用
      permission: {
        add: ['sys:role:save'],
        edit: ['sys:role:update'],
        del: ['sys:role:delete']
      },
      rules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        permission: [
          { required: true, message: '请输入权限', trigger: 'blur' }
        ]
      },
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    }
  },
  created() {
    getMenuList().then(res => {
      this.menus = list_to_vuetree(res.data.list, 'menuId', 'name');
    });
    this.crud.optShow = {
      add: true,
      edit: true,
      del: true,
      download: false,
      reset: true,
    };
  },
  methods: {
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        this.currentId = val.roleId
        var idx = val.menuIdList.indexOf(this.tempKey)
        if (idx !== -1) {
          val.menuIdList.splice(idx, val.menuIdList.length - idx)
        }
        this.$refs.menu.setCheckedKeys(val.menuIdList)
        this.showButton = true
      }
    },

    [CRUD.HOOK.beforeBatchToEdit]() {
      console.log(22222)
      this.currentId = this.crud.selections[0].roleId
      var idx = this.crud.selections[0].menuIdList.indexOf(this.tempKey)
      if (idx !== -1) {
        this.crud.selections[0].menuIdList.splice(idx, this.crud.selections[0].menuIdList.length - idx)
      }
      this.$refs.menu.setCheckedKeys(this.crud.selections[0].menuIdList)
      this.showButton = true
    },
    menuChange(menu) {
      console.log(menu.menuId)
      // this.$refs.menu.setCheckedKeys(this.menuIdList)
      // this.menuIdList = [].concat(this.$refs.menu.getCheckedKeys(), [this.tempKey], this.$refs.menu.getHalfCheckedKeys())
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const role = {
        roleId: this.currentId,
        menuIdList: [].concat(this.$refs.menu.getCheckedKeys(), [this.tempKey], this.$refs.menu.getHalfCheckedKeys())
      }

      crudRoles.edit(role).then(() => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.menuLoading = false
        this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err)
      })
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      crudRoles.get(this.currentId).then(res => {
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.roleId === this.crud.data[i].roleId) {
            this.crud.data[i] = res
            break
          }
        }
      })
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === '自定义') {
        this.getDepts()
      }
    },
    checkboxT(row) {
      return row.level >= this.level
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
 ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
 ::v-deep .vue-treeselect__multi-value{
    margin-bottom: 0;
  }
 ::v-deep .vue-treeselect__multi-value-item{
    border: 0;
    padding: 0;
  }
</style>
